#!/bin/bash

# ================================================================
# boost:http://sourceforge.net/projects/boost/files/boost/1.59.0/boost_1_59_0.tar.gz
# mysql 5.7:http://dev.mysql.com/downloads/mysql/5.7.html
#
# 下载mysql 5.7，然后解压，进入该目录
# 并在该mysql目录里，下载boost_1.59.0.tar.gz并解压
# 进入mysql的目录里，在运行此脚本
#
# ================================================================

# 一定要使用 bash 运行脚本，才能兼容source引入
wget https://gitee.com/zhp1221/linux-shell/raw/master/common_func.sh -O /tmp/common_func.sh

source /tmp/common_func.sh

echo_full_line
echo "安装c工具"
echo_full_line

curl -fsSL https://gitee.com/zhp1221/linux-shell/blob/master/c_utils.sh | sh

#if ! command -v zsh >/dev/null 2>&1; then
#    sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
#fi

# 开始mysql的处理
mkdir build
cd build
cmake .. \
    -DWITH_BOOST=../boost_1_59_0 \
    -DCMAKE_BUILD_TYPE=Debug \
    -DCMAKE_C_FLAGS="-O0 -g3" \
    -DCMAKE_CXX_FLAGS="-O0 -g3" \
    -DCMAKE_INSTALL_PREFIX=/usr/local/mysql \
    -DMYSQL_DATADIR=/usr/local/mysql/data \
    -DWITH_DEBUG=1 \
    -DWITH_INNOBASE_STORAGE_ENGINE=1 \
    -DWITH_SSL=system \
    -DDEFAULT_CHARSET=utf8mb4 \
    -DDEFAULT_COLLATION=utf8mb4_general_ci

make -j$(nproc)

sudo make install

sudo groupadd mysql
sudo useradd -r -g mysql -s /bin/false mysql

sudo mkdir -p /usr/local/mysql/data
sudo chown -R mysql:mysql /usr/local/mysql

cd /usr/local/mysql

sudo ln -sf /usr/local/mysql/bin/mysqld /usr/bin/mysqld
sudo ln -sf /usr/local/mysql/bin/mysql /usr/bin/mysql
sudo ln -sf /usr/local/mysql/bin/mysqladmin /usr/bin/mysqladmin
sudo ln -sf /usr/local/mysql/bin/mysqldump /usr/bin/mysqldump
sudo ln -sf /usr/local/mysql/bin/mysqlcheck /usr/bin/mysqlcheck
sudo ln -sf /usr/local/mysql/bin/mysqlshow /usr/bin/mysqlshow
sudo ln -sf /usr/local/mysql/bin/mysqlimport /usr/bin/mysqlimport

# 初始化数据库 （* 注意保存临时密码：ueEa><Oqr7Id）
sudo bin/mysqld --initialize --user=mysql --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data

mysqld --user=mysql

# 后续流程
# 新起一个shell：mysql -u root -p --socket=/usr/local/mysql/tmp/mysql.sock
# 输入临时密码：ueEa><Oqr7Id
# ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
# FLUSH PRIVILEGES;
# 优雅关闭（使得数据库可以自己 清理资源 持久化数据 避免 二次启动恢复时间变长）
# mysqladmin -u root -p shutdown --socket=/usr/local/mysql/tmp/mysql.sock